<template>
  <view class="room-result-container">
    <view class="page-header">
      <text class="page-title">房间结果</text>
      <text class="page-subtitle">房间: {{ roomName }}</text>
    </view>

    <view class="result-list-section">
      <view class="list-header">
        <text class="section-title">结果列表</text>
        <view class="header-actions">
          <button class="create-btn" @click="openAddResultModal">添加结果</button>
          <text class="list-count">共 {{ resultList.length }} 条结果</text>
        </view>
      </view>

      <view v-if="loading" class="loading-container">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="resultList.length === 0" class="empty-state">
        <text>该房间下暂无比赛结果</text>
      </view>

      <view v-else class="result-list">
        <view 
          class="result-item" 
          v-for="result in resultList" 
          :key="result.id"
        >
          <view class="result-header">
            <text class="result-id">结果ID: {{ result.id }}</text>
            <view class="result-score">
              <text class="score-label">分数:</text>
              <text class="score-value">{{ result.score || 0 }}</text>
            </view>
          </view>
          
          <view class="result-info">
            <view class="info-row">
              <text class="info-label">席位ID:</text>
              <text class="info-value">{{ result.matchRoomSeatId || '未设置' }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">完成时间:</text>
              <text class="info-value">{{ formatTime(result.time) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">步数:</text>
              <text class="info-value">{{ result.step || 0 }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">比赛位置:</text>
              <text class="info-value">{{ result.matchPos || 1 }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">作弊类型:</text>
              <text class="info-value">{{ getCheatTypeText(result.cheatType) }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">创建时间:</text>
              <text class="info-value">{{ formatDate(result.createTime) }}</text>
            </view>
          </view>
          
          <view class="result-actions">
            <button class="edit-btn" @click="editResult(result)">编辑</button>
            <button class="delete-btn" @click="deleteResult(result)">删除</button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加/编辑结果模态框 -->
    <view class="modal-overlay" v-if="showResultFormModal" @click="closeResultFormModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEditingResult ? '编辑结果' : '添加结果' }}</text>
          <button class="close-btn" @click="closeResultFormModal">×</button>
        </view>
        
        <view class="modal-body">
          <view class="form-section">
            <view class="form-item">
              <text class="form-label">席位ID</text>
              <input 
                class="form-input" 
                v-model="resultForm.matchRoomSeatId" 
                placeholder="请输入席位ID"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">分数</text>
              <input 
                class="form-input" 
                v-model="resultForm.score" 
                type="number"
                placeholder="请输入分数"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">完成时间(毫秒)</text>
              <input 
                class="form-input" 
                v-model="resultForm.time" 
                type="number"
                placeholder="请输入完成时间"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">步数</text>
              <input 
                class="form-input" 
                v-model="resultForm.step" 
                type="number"
                placeholder="请输入步数"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">比赛位置</text>
              <input 
                class="form-input" 
                v-model="resultForm.matchPos" 
                type="number"
                placeholder="请输入比赛位置"
              />
            </view>
            
            <view class="form-item">
              <text class="form-label">作弊类型</text>
              <view class="form-picker" @click="openCheatTypePicker">
                <view class="picker-text">{{ cheatTypeOptions[cheatTypeIndex] || '请选择作弊类型' }}</view>
                <view class="picker-arrow">▼</view>
              </view>
            </view>
            
            <view class="form-item">
              <text class="form-label">房间规则ID</text>
              <input 
                class="form-input" 
                v-model="resultForm.matchRoomRuleId" 
                placeholder="请输入房间规则ID"
              />
            </view>
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeResultFormModal">取消</button>
          <button class="submit-btn" @click="saveResult" :disabled="submitting">
            {{ submitting ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 作弊类型选择模态框 -->
    <view class="modal-overlay" v-if="showCheatTypePicker" @click="closeCheatTypePicker">
      <view class="picker-modal-content" @click.stop>
        <view class="picker-modal-header">
          <text class="picker-modal-title">选择作弊类型</text>
          <button class="close-btn" @click="closeCheatTypePicker">×</button>
        </view>
        <view class="picker-modal-body">
          <view 
            class="picker-option" 
            v-for="(option, index) in cheatTypeOptions" 
            :key="index"
            @click="selectCheatType(index)"
            :class="{ 'selected': cheatTypeIndex === index }"
          >
            <text class="option-text">{{ option }}</text>
            <view class="option-check" v-if="cheatTypeIndex === index">✓</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomResultAPI } from '@/api/battle.js'

const loading = ref(false)
const resultList = ref([])
const roomId = ref('')
const roomName = ref('')

// 结果表单相关数据
const showResultFormModal = ref(false)
const submitting = ref(false)
const isEditingResult = ref(false)
const currentResult = ref(null)

// 选择器相关数据
const showCheatTypePicker = ref(false)
const cheatTypeIndex = ref(0)

// 结果表单数据
const resultForm = ref({
  matchRoomSeatId: '',
  score: '',
  time: '',
  step: '',
  matchPos: 1,
  cheatType: 0,
  matchRoomRuleId: ''
})

// 作弊类型选项
const cheatTypeOptions = [
  '无作弊',
  '使用辅助工具',
  '提前查看题目',
  '多人协作',
  '其他'
]

// 作弊类型映射
const cheatTypeMap = {
  0: '无作弊',
  1: '使用辅助工具',
  2: '提前查看题目',
  3: '多人协作',
  4: '其他'
}

const getCheatTypeText = (cheatType) => cheatTypeMap[cheatType] || '未知'

const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

const formatTime = (time) => {
  if (!time) return '未设置'
  const seconds = Math.floor(time / 1000)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  const milliseconds = time % 1000
  
  if (minutes > 0) {
    return `${minutes}分${remainingSeconds}秒${milliseconds}毫秒`
  } else {
    return `${remainingSeconds}秒${milliseconds}毫秒`
  }
}

const fetchResultList = async () => {
  if (!roomId.value) return;
  loading.value = true
  try {
    const result = await MatchRoomResultAPI.page({ 
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 100
    })
    console.log('结果查询API返回结果:', result)
    if (result.code === 0) {
      resultList.value = result.data?.list || result.data || []
    } else {
      resultList.value = []
      throw new Error(result.msg || '获取结果失败')
    }
  } catch (error) {
    console.error('获取结果失败:', error)
    uni.showToast({
      title: error.message || '获取结果失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
    roomName.value = decodeURIComponent(options.roomName || '')
    fetchResultList()
  }
})

// 编辑结果
const editResult = (result) => {
  isEditingResult.value = true
  currentResult.value = result
  fillResultForm(result)
  showResultFormModal.value = true
}

// 删除结果
const deleteResult = (result) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除结果 "${result.id}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchRoomResultAPI.remove({
            matchRoomResultId: result.id
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            fetchResultList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除结果失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 打开添加结果模态框
const openAddResultModal = () => {
  isEditingResult.value = false
  currentResult.value = null
  resetResultForm()
  showResultFormModal.value = true
}

// 关闭结果表单模态框
const closeResultFormModal = () => {
  showResultFormModal.value = false
  isEditingResult.value = false
  currentResult.value = null
  resetResultForm()
}

// 重置结果表单
const resetResultForm = () => {
  resultForm.value = {
    matchRoomSeatId: '',
    score: '',
    time: '',
    step: '',
    matchPos: 1,
    cheatType: 0,
    matchRoomRuleId: ''
  }
  cheatTypeIndex.value = 0
}

// 填充结果表单
const fillResultForm = (result) => {
  resultForm.value = {
    matchRoomSeatId: result.matchRoomSeatId || '',
    score: result.score || '',
    time: result.time || '',
    step: result.step || '',
    matchPos: result.matchPos || 1,
    cheatType: result.cheatType || 0,
    matchRoomRuleId: result.matchRoomRuleId || ''
  }
  cheatTypeIndex.value = result.cheatType || 0
}

// 打开作弊类型选择器
const openCheatTypePicker = () => {
  showCheatTypePicker.value = true
}

// 关闭作弊类型选择器
const closeCheatTypePicker = () => {
  showCheatTypePicker.value = false
}

// 选择作弊类型
const selectCheatType = (index) => {
  cheatTypeIndex.value = index
  resultForm.value.cheatType = index
  closeCheatTypePicker()
}

// 保存结果
const saveResult = async () => {
  if (!resultForm.value.matchRoomSeatId.trim()) {
    uni.showToast({
      title: '请输入席位ID',
      icon: 'none'
    })
    return
  }
  
  if (!resultForm.value.score || resultForm.value.score < 0) {
    uni.showToast({
      title: '请输入有效分数',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const data = {
      matchRoomId: roomId.value,
      matchRoomSeatId: resultForm.value.matchRoomSeatId,
      score: parseInt(resultForm.value.score),
      time: parseInt(resultForm.value.time) || 0,
      step: parseInt(resultForm.value.step) || 0,
      matchPos: parseInt(resultForm.value.matchPos) || 1,
      cheatType: resultForm.value.cheatType,
      matchRoomRuleId: resultForm.value.matchRoomRuleId
    }
    
    let result
    if (isEditingResult.value) {
      result = await MatchRoomResultAPI.edit({
        ...data,
        matchRoomResultId: currentResult.value.id
      })
    } else {
      result = await MatchRoomResultAPI.create(data)
    }
    
    if (result.code === 0) {
      uni.showToast({
        title: isEditingResult.value ? '更新成功' : '创建成功',
        icon: 'success'
      })
      closeResultFormModal()
      fetchResultList()
    } else {
      throw new Error(result.msg || (isEditingResult.value ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('保存结果失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.room-result-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.result-list-section {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .section-title {
      color: #fff;
      font-size: 32rpx;
      font-weight: bold;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 15rpx;
      
      .create-btn {
        height: 60rpx;
        padding: 0 25rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
      }
      
      .list-count {
        color: rgba(255, 255, 255, 0.8);
        font-size: 24rpx;
      }
    }
  }

  .loading-container, .empty-state {
    text-align: center;
    color: #fff;
    padding: 50rpx;
  }
  
  .result-list .result-item {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 40rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
      
    .result-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      
      .result-id {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .result-score {
        display: flex;
        align-items: center;
        
        .score-label {
          font-size: 24rpx;
          color: #666;
          margin-right: 10rpx;
        }
        
        .score-value {
          font-size: 36rpx;
          font-weight: bold;
          color: #28a745;
        }
      }
    }
      
    .result-info {
      .info-row {
        display: flex;
        margin-bottom: 15rpx;
        font-size: 26rpx;
        
        .info-label { 
          width: 160rpx; 
          color: #666; 
        }
        .info-value { 
          flex: 1; 
          color: #333; 
        }
      }
    }
    
    .result-actions {
      display: flex;
      gap: 15rpx;
      justify-content: flex-end;
      margin-top: 20rpx;
      
      .edit-btn, .delete-btn {
        padding: 8rpx 20rpx;
        border: none;
        border-radius: 12rpx;
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
      }
      
      .edit-btn {
        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
      }
      
      .delete-btn {
        background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
      }
    }
  }
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 选择器模态框样式
.picker-modal-content {
  width: 80%;
  max-height: 70%;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  z-index: 10001;
  
  .picker-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #eee;
    background: #f8f9fa;
    
    .picker-modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      border: none;
      background: none;
      font-size: 40rpx;
      color: #999;
    }
  }
  
  .picker-modal-body {
    max-height: 50vh;
    overflow-y: auto;
    
    .picker-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #eee;
      transition: background-color 0.3s ease;
      
      &:hover {
        background: #f8f9fa;
      }
      
      &.selected {
        background: #e3f2fd;
        border-left: 4rpx solid #007bff;
      }
      
      .option-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .option-check {
        font-size: 32rpx;
        color: #007bff;
        font-weight: bold;
      }
    }
  }
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .modal-content {
    width: 90%;
    max-height: 80%;
    background: #fff;
    border-radius: 20rpx;
    overflow: hidden;
    position: relative;
    z-index: 10000;
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 2rpx solid #eee;
      
      .modal-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        width: 60rpx;
        height: 60rpx;
        border: none;
        background: none;
        font-size: 40rpx;
        color: #999;
      }
    }
    
    .modal-body {
      padding: 30rpx;
      max-height: 60vh;
      overflow-y: auto;
      
      .form-section {
        .form-item {
          margin-bottom: 25rpx;
          position: relative;
          z-index: 1;
          
          .form-label {
            display: block;
            font-size: 26rpx;
            color: #333;
            font-weight: bold;
            margin-bottom: 10rpx;
          }
          
          .form-input {
            width: 100%;
            height: 70rpx;
            padding: 0 15rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            font-size: 26rpx;
            background: #fff;
            box-sizing: border-box;
            
            &:focus {
              border-color: #667eea;
            }
          }
          
          .form-picker {
            width: 100%;
            height: 70rpx;
            border: 2rpx solid #ddd;
            border-radius: 8rpx;
            background: #fff;
            position: relative;
            z-index: 2;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 15rpx;
            cursor: pointer;
            box-sizing: border-box;
            
            .picker-text {
              font-size: 26rpx;
              color: #333;
            }
            
            .picker-arrow {
              font-size: 24rpx;
              color: #999;
            }
          }
        }
      }
    }
    
    .modal-footer {
      display: flex;
      gap: 20rpx;
      padding: 30rpx;
      border-top: 2rpx solid #eee;
      
      .cancel-btn, .submit-btn {
        flex: 1;
        height: 80rpx;
        border: none;
        border-radius: 12rpx;
        font-size: 28rpx;
        font-weight: bold;
        
        &.cancel-btn {
          background: #f8f9fa;
          color: #666;
          border: 2rpx solid #eee;
        }
        
        &.submit-btn {
          background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
          color: #fff;
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
  }
}
</style> 